﻿using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.IO.Compression;

namespace FreeBroker
{
    public class Communication
    {
        public Image godmodeGetImage(string id, string dauer)
        {
            string test = "log,line,86400,0,0," + dauer + ",0,0,30;iMACDWH,12,26,9;";
            string exchange = "4";
            string t = "UHJvZmljaGFydA%3D%3D";
            TimeSpan time = DateTime.UtcNow - new DateTime(1970, 1, 1);
            string r = time.TotalMilliseconds.ToString();
            DateTime ts = DateTime.FromFileTimeUtc((long)time.TotalMilliseconds);
            Console.WriteLine(" >>>  Time to ask for: " + ts.ToLongDateString() + "  " + ts.ToLongTimeString());

            string q = Helper.base64Encode(test);
            string o = "0";
            string theme = "gmt";
            r = "29030400";
            string request = "http://www.godmode-trader.de/front/img/charts/detailchart/chart.php?exchange=" + exchange + "&id=" + id + "&t=" + t + "&r=" + r + "&q=" + q + "&o=" + o + "&theme=" + theme;
            string referer = "http://www.godmode-trader.de/front/index.php";
            return requestImage(request, referer);
        }

        public Image comdirektGetImage(string symbol)
        {
            string request = "http://isht.comdirect.de/charts/big.chart?hist=1y&type=CONNECTLINE&avg1=38&avg2=200&ind0=VOLUME&&currency=&&lSyms=" + symbol + "&lColors=0x000000&sSym=" + symbol + "&hcmask=";
            string referer = "http://isht.comdirect.de/html/detail/main.html?sTab=chart&sCat=STK&sSym=" + symbol;
            return requestImage(request, referer);
        }

        public Image requestImage(string req, string referer)
        {
            HttpWebResponse res = null;
            for (int i = 0; i < 10; i++)
            {

                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.godmode-trader.de/front/img/charts/chart.php?tpl=profilechart&intv=" + r + "&id=" + id + "&exchange="+exchange + "&hideVolume=true");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(req);
                request.Accept = "image/png,image/*;q=0.8,*/*;q=0.5";
                request.Method = "GET";
                request.Timeout = 60000;
                request.ReadWriteTimeout = 60000;
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7";
                request.Headers.Add("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
                request.Headers.Add("Accept-Encoding", "gzip,deflate");
                request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                request.ContentType = "";
                request.Headers.Add("Keep-Alive", "300");
                request.Referer = referer;
                Uri uri = new Uri(request.Referer);
                //request.CookieContainer = new CookieContainer();
                //request.CookieContainer.Add(uri, new Cookie("BGO_Last_visisted_instruments", id));
                //request.Headers.Add("Cookie", "BGO_Last_visisted_instruments=" + id);
                request.KeepAlive = true;
                try
                {
                    res = (HttpWebResponse)request.GetResponse();
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Problem: " + e.Message);
                    Thread.Sleep(1000);
                }
            }
            if (res != null)
            {
                try
                {
                    Stream imgStream = res.GetResponseStream();
                    if (res.ContentType.Contains("image"))
                    {
                        Image img = Image.FromStream(imgStream);
                        return img;
                    }
                    else
                    {
                        Console.WriteLine("No image received !");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
                finally
                {
                    if (res != null)
                    {
                        res.Close();
                    }
                }

            }
            return null;
        }

        /// <summary>
        ///     Sends a POST request with the given search query.
        /// </summary>
        /// <param name="search"></param>
        /// <returns>the ID of the searched chart name</returns>
        public string comdirectPostSearch(string search)
        {
            string request = "http://isht.comdirect.de/html/search/main.html";
            string referer = "http://www.comdirect.de/navigation.html";
            string searchQuery = "cbAktien=checked&cbOther=checked&sWpType=FND&sSearchterm=" + search + "&x=8&y=5";
            string content = postSearchComdirect(request, referer, searchQuery);
            return content;
            //return Helper.extractUrlAttribute(link, "Sym");
        }

        public Image comdirectImage(string req, string cookies)
        {
            if (req == null)
            {
                Console.WriteLine("Request is NULL !");
                return null;
            }
            HttpWebResponse res = null;
            for (int i = 0; i < 3; i++)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(req);
                request.Accept = "image/png,image/*;q=0.8,*/*;q=0.5";
                request.Method = "GET";
                request.Timeout = 60000;
                request.ReadWriteTimeout = 60000;
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7";
                request.Headers.Add("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
                request.Headers.Add("Accept-Encoding", "gzip,deflate");
                request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                request.Headers.Add("Keep-Alive", "115");
                request.Referer = "http://www.comdirect.de";
                request.Headers.Add("Cookie", "qSession=85.177.9.9.1285525235749561; AdvertisingId=201016860000000TS0000900000000#1288117236");
                request.KeepAlive = true;
                try
                {
                    res = (HttpWebResponse)request.GetResponse();
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Problem: " + e.Message);
                    Thread.Sleep(1000);
                }
            }
            if (res != null)
            {
                try
                {
                    Stream imgStream = res.GetResponseStream();
                    if (res.ContentType.Contains("image"))
                    {
                        Image img = Image.FromStream(imgStream);
                        return img;
                    }
                    else
                    {
                        Console.WriteLine("No image received !");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
                finally
                {
                    if (res != null)
                    {
                        res.Close();
                    }
                }

            }
            return null;
        }

        public string GetSearchComdirect(string req)
        {
            return SendGetRequest(req);
        }

        public string postSearchComdirect(string req, string referer, string searchQuery)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(req);
            request.Timeout = 60000;
            request.ReadWriteTimeout = 60000;
            request.Method = "POST";
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Headers.Add("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
            request.Headers.Add("Accept-Encoding", "gzip,deflate");
            request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            request.Headers.Add("Keep-Alive", "300");
            request.KeepAlive = true;
            request.MaximumAutomaticRedirections = 2;
            request.Referer = referer;
            request.Headers.Add("Cookie", "AdvertisingId=200816860000000TS0000900000000#1224185482; lPageState_chart=extended; lPageState_bigchart=extended; qSession=85.177.0.51.1221593394345091");
            request.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse res = null;
            try
            {
                byte[] searchBytes = new byte[searchQuery.Length];
                request.ContentLength = searchBytes.Length;
                Stream str = request.GetRequestStream();

                searchBytes = System.Text.Encoding.UTF8.GetBytes(searchQuery);
                str.Write(searchBytes, 0, searchBytes.Length);

                // Set credentials to use for this request.
                request.Credentials = CredentialCache.DefaultCredentials;

                Thread.Sleep(1000);
                res = (HttpWebResponse)request.GetResponse();

                if (res != null)
                {
                    Stream myStream = res.GetResponseStream();
                    GZipStream zipStream = new GZipStream(myStream, CompressionMode.Decompress);
                    StreamReader sr = new StreamReader(zipStream);
                    return sr.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem: " + e.Message);
                Thread.Sleep(1000);
            }
            finally
            {
                if (res != null)
                {
                    res.Close();
                }
            }
            return null;
        }

        /// <summary>
        ///     Sends a POST request with the given search query.
        /// </summary>
        /// <param name="search"></param>
        /// <returns>the ID of the searched chart name</returns>
        public string postSearch(string req, string referer, string searchQuery, ref string content)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(req);
            request.Timeout = 60000;
            request.ReadWriteTimeout = 60000;
            request.Method = "POST";
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Headers.Add("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
            request.Headers.Add("Accept-Encoding", "gzip,deflate");
            request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            request.ContentType = "application/x-www-form-urlencoded";
            request.KeepAlive = true;
            request.Headers.Add("Keep-Alive", "300");
            
            request.MaximumAutomaticRedirections = 2;
            //request.Expect = null;
            request.Referer = referer;
            HttpWebResponse res = null;
            try
            {
                byte[] searchBytes = new byte[searchQuery.Length];
                request.ContentLength = searchBytes.Length;
                Stream str = request.GetRequestStream();

                searchBytes = Encoding.UTF8.GetBytes(searchQuery);
                str.Write(searchBytes, 0, searchBytes.Length);

                // Set credentials to use for this request.
                request.Credentials = CredentialCache.DefaultCredentials;

                res = (HttpWebResponse)request.GetResponse();

                if (res != null)
                {
                    Stream myStream = res.GetResponseStream();
                    StreamReader sr = new StreamReader(myStream);
                    content = sr.ReadToEnd();
                    string link = res.ResponseUri.OriginalString;
                    return link;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem: " + e.Message);
                Thread.Sleep(1000);
            }
            finally
            {
                if (res != null)
                {
                    res.Close();
                }
            }
            return null;
        }

        /// <summary>
        ///     Sends a GET request.
        /// </summary>
        /// <param name="search"></param>
        /// <returns>the content of the response page</returns>
        public string SendGetRequest(string req)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(req);
            request.Timeout = 60000;
            request.ReadWriteTimeout = 60000;
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Headers.Add("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
            request.Headers.Add("Accept-Encoding", "gzip,deflate");
            request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            request.ContentType = "application/x-www-form-urlencoded";
            request.KeepAlive = true;
            request.Headers.Add("Keep-Alive", "300");

            request.MaximumAutomaticRedirections = 2;
            //request.Expect = null;
            request.Referer = req;
            HttpWebResponse res = null;
            try
            {
                // Set credentials to use for this request.
                request.Credentials = CredentialCache.DefaultCredentials;
                res = (HttpWebResponse)request.GetResponse();
                if (res != null)
                {
                    Stream myStream = res.GetResponseStream();
                    StreamReader sr;
                    if (res.ContentEncoding.Equals("gzip", StringComparison.CurrentCultureIgnoreCase))
                    {
                        GZipStream gzip = new GZipStream(myStream, CompressionMode.Decompress);
                        sr = new StreamReader(gzip);
                    }
                    else
                    {
                        sr = new StreamReader(myStream);
                    }
                    return sr.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem: " + e.Message);
                Thread.Sleep(1000);
            }
            finally
            {
                if (res != null)
                {
                    res.Close();
                }
            }
            return null;
        }
    }
}
